<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-08-20 09:37:05
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ref, unref, watch, reactive } from 'vue'
import { ElOption, ElSelect, ElTree, ElInput, ElMessage } from 'element-plus'
import SCADAApi from '@/api/scada'
import { useSearch } from '@/hooks/web/useSearch'
import { Echart } from '@/components/Echart'
import { HistoryOptions } from './components/echarts-data'
import { EChartsOption } from 'echarts'
import { DTUAttributeList } from '@/api/scada/type'
import { set } from 'lodash-es'
import dayjs from 'dayjs'
import {
  FlowmeterColumn,
  TransmitterColumn,
  FlowmeterOption,
  TransmitterOption
} from './components/echarts-data'
import { useTable } from '@/hooks/web/useTable'
import { TableColumn } from '@/components/Table'
import { HistorySearchParams } from './components/type'
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref<any>() //树结构ID
const departmentList = ref<any>([]) //树结构数据
const { t } = useI18n()
const fetchDepartment = async () => {
  const res = await SCADAApi.GetMarTreeData()
  departmentList.value = res
  currentNodeKey.value = res[0]?.onlyKey || null //树结构ID也为第一个
  unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)
const searchParams = ref<HistorySearchParams | null>(null)
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await SCADAApi.GetHistoryData({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows,
      total: res.total
    }
  },
  immediate: false // 关闭初始化自动请求
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const { searchRegister, searchMethods } = useSearch()
const { setValues } = searchMethods
//树结构点击
const currentChange = (data: any) => {
  currentNodeKey.value = data.onlyKey
  if (data['devName']) {
    setValues(data)
  } else {
    data['devName'] = ''
    setValues(data)
  }
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.siteName.includes(value) || data.deviceNo.includes(value)
}
//s搜索结构
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'siteName',
    label: t('选择站点'),
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '选择站点'
    }
  },
  {
    field: 'devName',
    label: t('选择设备'),
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '选择设备'
    }
  },
  {
    field: 'interval',
    label: t('间隔'),
    component: 'Select',
    componentProps: {
      placeholder: '间隔',
      options: [
        {
          label: '1分钟',
          value: 1
        },
        {
          label: '5分钟',
          value: 5
        },
        {
          label: '10分钟',
          value: 10
        },
        {
          label: '30分钟',
          value: 30
        },
        {
          label: '30分钟',
          value: 30
        }
      ]
    }
  },
  {
    field: 'DatePicker',
    label: t('时间范围'),
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      valueFormat: 'YYYY-MM-DD'
    }
  }
])
//下拉菜单曲线默认值
const SelectValue = ref('曲线')
//下拉菜单子菜单
const options: any = ref([])
//下拉菜单隐藏
const SelectVisible = ref(false)
//曲线弹出框隐藏
const dialogVisible = ref(false)
//表格表头结构
let columns = reactive<TableColumn[]>([])
//搜索框查询
const setSearchParams = async (data: any) => {
  console.log(data)
  if (data.devName) {
    searchParams.value = {
      // deviceNo: "20250618003",
      deviceNo: data.deviceNo,
      devNo: data.devNo,
      devType: data.devType,
      startDate: data.DatePicker[0],
      endDate: data.DatePicker[1],
      devName: data.devName,
      interval: data.interval
    }
    if (data.devType == 0) {
      columns = FlowmeterColumn(data.devName)
      options.value = FlowmeterOption()
    } else {
      columns = TransmitterColumn(data.devName)
      options.value = TransmitterOption()
    }
    SelectVisible.value = true
    getList()
  } else {
    ElMessage.error('未选择设备')
  }
}
const OptionsData = reactive<EChartsOption>(HistoryOptions) as EChartsOption
const getMonthlySales = async (res: DTUAttributeList[], label: string) => {
  const time = res.map((item: DTUAttributeList) => {
    return dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')
  })
  const value = res.map((item: DTUAttributeList) => {
    return item.value
  })
  set(OptionsData, 'xAxis.data', time)
  set(OptionsData, 'legend.data', [`${searchParams.value?.devName}--${label}`])
  set(OptionsData, 'series', [
    {
      name: `${searchParams.value?.devName}--${label}`,
      smooth: true,
      type: 'line',
      data: value
    }
  ])
}
//下拉菜单点击曲线
const selectChange = async (key: number) => {
  const i = await SCADAApi.GetAttributeListData({
    aFfectField: key,
    ...unref(searchParams)
  })
  const selectedOption = options.value.find((item: any) => item.value === key)
  getMonthlySales(i, selectedOption.label)
  SelectValue.value = '曲线'
  dialogVisible.value = true
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="站点选择">
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('搜索站点名称/编号')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        :expand-on-click-node="false"
        node-key="onlyKey"
        accordion
        :current-node-key="currentNodeKey"
        :props="{
          label: 'siteName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div
            v-if="data.devName"
            :title="data.devName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.devName }}
          </div>
          <div
            v-else
            :title="data.siteName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.siteName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" title="历史数据">
      <Search
        :schema="searchSchema"
        @search="setSearchParams"
        @register="searchRegister"
        @reset="setSearchParams"
      />
      <ElSelect
        v-if="SelectVisible"
        @change="selectChange"
        v-model="SelectValue"
        style="width: 140px; margin-bottom: 18px"
      >
        <ElOption
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
      <Table
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="columns"
        :data="dataList"
        :loading="loading"
        sortable
        :pagination="{
          total: total
        }"
        @register="tableRegister"
      />
      <Dialog style="width: 70%" v-model="dialogVisible" title="曲线">
        <Echart :options="OptionsData" height="90%" />
        <template #footer>
          <BaseButton type="primary" @click="dialogVisible = false">
            {{ t('exampleDemo.save') }}
          </BaseButton>
          <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
        </template>
      </Dialog>
    </ContentWrap>
  </div>
</template>
<style scoped lang="less">
:deep(.el-scrollbar__view) {
  height: 100%;
}
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
:deep(.el-range-editor--small) {
  height: 29px !important;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
